package com.basksoft.server.demo.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import com.basksoft.core.model.datasource.ConnectionProvider;
import com.basksoft.server.demo.ToolSpring;

/**
 * @author William.Jiang
 * @since 2020年11月26日
 */

public class TestConnectionProvider implements ConnectionProvider {
	private static Properties properties = null;
	private static DataSource dataSource;
	// 加载DBCP配置文件
	static {
		properties = new Properties();
		properties.put("username", getProperty("baskserver.sampledb.username"));
		properties.put("password", getProperty("baskserver.sampledb.password"));
		properties.put("driverClassName", getProperty("baskserver.sampledb.driverClassName"));
		properties.put("url",getProperty("baskserver.sampledb.url"));
		try {
			dataSource = BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String getProperty(String key) {
		String result = ToolSpring.getEnvironment().getProperty(key);
 		return result;
	}

	public Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
}
